package rank

import (
	"context"
	"github.com/hwcer/cosgo/scc"
	"github.com/hwcer/logger"
	"time"
)

var Master = master{}

type master map[string]*Bucket

func (this master) Get(name string) *Bucket {
	return this[name]
}

func (this master) Register(name string, zMax, zScore int64, zType SortType, handle Handle) {
	if _, ok := this[name]; ok {
		logger.Fatal("重复注册排行榜:%v", name)
	}
	this[name] = NewBucket(name, zMax, zScore, zType, handle)
}

func (this master) start() (err error) {
	for _, bucket := range this {
		if err = bucket.start(); err != nil {
			return
		}
	}
	scc.CGO(this.heartbeat)
	return
}

func (this master) heartbeat(ctx context.Context) {
	v := time.Second * Heartbeat
	t := time.NewTimer(v)
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			this.worker()
			t.Reset(v)
		}
	}
}

func (this master) worker() {
	defer func() {
		if e := recover(); e != nil {
			logger.Error(e)
		}
	}()
	for _, bucket := range this {
		bucket.heartbeat()
	}
}
